package com.neu.questionnaire_system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neu.questionnaire_system.beans.ResponseEntity;
import com.neu.questionnaire_system.entity.Answer;
import com.neu.questionnaire_system.entity.Questionnaire;
import com.neu.questionnaire_system.entity.User;
import com.neu.questionnaire_system.mapper.AnswerMapper;
import com.neu.questionnaire_system.mapper.UserMapper;
import com.neu.questionnaire_system.service.AnswerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neu.questionnaire_system.util.Constants;
import com.neu.questionnaire_system.util.EmailSender;
import com.neu.questionnaire_system.util.UUIDGenerator;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.mail.EmailException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xingle
 * @since 2022-10-31
 */
@Service
public class AnswerServiceImpl extends ServiceImpl<AnswerMapper, Answer> implements AnswerService {

    @Autowired
    private AnswerMapper answerMapper;

    @Autowired
    private QuestionnaireServiceImpl questionnaireService;
    /*@Autowired
    private UserMapper userMapper;*/

    /**
     * created by jyh 2022-11-8
     *
     * @param map 从前端传入的data，注意map的key要时刻保持一致性
     * @return 返回一个结果给控制层
     */

    public ResponseEntity addAnswer(Map<String, Object> map) throws InvocationTargetException, IllegalAccessException {
        ResponseEntity responseEntity = new ResponseEntity();
        if (map.get("answerName") != null) {
            //需要写一个查询语句，判断答者是否存在，并返回一个值，用接收的值判断存在与否
            if (answerMapper.queryExistAnswer(map) != 0) {
                responseEntity.setCode(Constants.FAIL_CODE);
                responseEntity.setMessage(Constants.USERNAME_REPEAT_MESSAGE);//表示用户已经存在不能创建
                return responseEntity;
            }
        }
        //String id = tenantMapper.findTidByName(map.get("tenantName").toString());
        //map.put("tid",tid);
        String aid = UUIDGenerator.getOneUUID();//这个工具类不要导入错了，我自己写的在util包下
        Answer answer = new Answer();
        map.put("aid", aid);//将生成的uid加入map中。
        map.put("isDeleted", "0");
        BeanUtils.populate(answer, map);//用map中的元素封装user
        int res = answerMapper.insert(answer);
        responseEntity.setCode(Constants.SUCCESS_CODE);//封装状态码到返回的对象
        responseEntity.setMessage(Constants.ADD_MESSAGE);//封装状态消息到返回的对象
        return responseEntity;
    }

    /**
     * create by jyh用户主页展示答者信息
     *
     * @return 返回包含答者列表信息的对象
     */
    public ResponseEntity showAnswer() {

        ResponseEntity responseEntity = new ResponseEntity();
        responseEntity.setCode(Constants.SUCCESS_CODE);

        List<IPage<Map<String, Object>>> list = new ArrayList<>();

        int current = 1;
        long count = 0;
        while (count <= answerMapper.selectCount(null)) {
            IPage<Map<String, Object>> iPage = answerMapper.showAnswer(new Page<>(current, Constants.PAGE_SIZE));
            list.add(iPage);
            current++;
            count += iPage.getSize();
        }

        responseEntity.setData(list);
        responseEntity.setMessage(Constants.SELECT_MESSAGE);
        return responseEntity;
    }

    /**
     * created by jyh 删除答者
     *
     * @param map 被删除答者名
     * @return 返回统一的封装对象
     */
    public ResponseEntity deleteAnswer(Map<String, Object> map) {
        ResponseEntity responseEntity = new ResponseEntity();
        //String aid = answerMapper.queryAidByAnswerName(map.get("answerName").toString());
        String aid = map.get("aid").toString();
        int canDelete = answerMapper.ifAnswerCanDelete(map.get("aid").toString());
        if (canDelete > 0) {
            responseEntity.setCode(Constants.FAIL_CODE);//删除失败
            responseEntity.setMessage(Constants.DELETE_FAIL_MESSAGE);
            return responseEntity;
        }
        if (answerMapper.queryAnswerIsEmpty(map.get("aid").toString()) <= 0) {
            responseEntity.setCode(Constants.FAIL_CODE);//删除失败
            responseEntity.setMessage(Constants.DELETE_FAIL_MESSAGE);
            return responseEntity;
        } else {
            if (answerMapper.queryClusterByAid(aid) > 0) {
                responseEntity.setCode(Constants.FAIL_CODE);
                responseEntity.setMessage(Constants.USERNAME_FAIL_DELETE_MESSAGE);//删除失败，当前用户还关联着群组
                return responseEntity;
            }
        }
        int res = answerMapper.updateAnswerStatue("1", aid);
        if (res <= 0) {
            responseEntity.setCode(Constants.FAIL_CODE);//删除失败
            responseEntity.setMessage(Constants.DELETE_FAIL_MESSAGE);
            return responseEntity;
        }
        responseEntity.setCode(Constants.SUCCESS_CODE);
        responseEntity.setMessage(Constants.DELETE_MESSAGE);
        return responseEntity;
    }

    /**
     * created by jyh 根据答者名查询答者
     *
     * @param map 传入的map
     * @return 统一的返回对象
     */
    public ResponseEntity findAnswerByAnswerName(Map<String, Object> map) {
        ResponseEntity responseEntity = new ResponseEntity();
        responseEntity.setCode(Constants.SUCCESS_CODE);
        responseEntity.setData(answerMapper.findAnswerByAnswerName(map));
        responseEntity.setMessage(Constants.SELECT_MESSAGE);
        return responseEntity;
    }

    /**
     * created by jyh 更新答者信息
     *
     * @param map 传入的数据
     * @return 返回统一的封装对象
     */
    public ResponseEntity updateAnswer(Map<String, Object> map) {
        ResponseEntity responseEntity = new ResponseEntity();

        String aid = map.get("aid").toString();
        int canDelete = answerMapper.ifAnswerCanDelete(map.get("aid").toString());
        if (canDelete > 0) {
            responseEntity.setCode(Constants.FAIL_CODE);//删除失败
            responseEntity.setMessage(Constants.UPDATE_FAIL_MESSAGE);
            return responseEntity;
        }

        if (answerMapper.updateAnswer(map) > 0) {
            responseEntity.setCode(Constants.SUCCESS_CODE);
            responseEntity.setMessage(Constants.UPDATE_MESSAGE);
        } else {
            responseEntity.setCode(Constants.FAIL_CODE);
            responseEntity.setMessage(Constants.UPDATE_FAIL_MESSAGE);
        }
        return responseEntity;
    }


    /**
     * created by jyh 答者登录
     *
     * @param answerName,password,qid 传入的answer
     * @return 统一的对象
     */
    public ResponseEntity answerLogin(String answerName, String password, String qid) {
        ResponseEntity responseEntity = new ResponseEntity();
        boolean bool1 = this.isAnsweredQuestionnaire(answerName, qid);
        boolean bool2 = questionnaireService.isQuestionnaireOpen(qid);
        Map<String, Object> map = new HashMap<>();
        map.put("answerName", answerName);
        map.put("password", password);
        Answer answer1 = answerMapper.queryAnswerInfo(answerName, password);
        Questionnaire questionnaire = questionnaireService.selectByQid(qid);

        if (questionnaire.getAnsweredCount() >= questionnaire.getAnswerCount()) {
            responseEntity.setCode(Constants.FAIL_CODE);
            responseEntity.setMessage("此问卷答卷次数已达上限，登陆失败！");
            return responseEntity;
        }
        if (answer1 != null && !bool1 && bool2) {
            int res = answerMapper.findAnswerCluster(answer1.getAid(), qid);
            if (res > 0) {
                responseEntity.setCode(Constants.SUCCESS_CODE);
                responseEntity.setData(answer1);
                responseEntity.setMessage(Constants.LOGIN_SUCCESS_MESSAGE);
                return responseEntity;
            } else {
                responseEntity.setCode(Constants.FAIL_CODE);
                responseEntity.setMessage("此用户不再此问卷的群组之中，无法登录答题！");
                return responseEntity;
            }
        } else if (bool1) {
            responseEntity.setCode(Constants.FAIL_CODE);
            responseEntity.setMessage(Constants.ANSWER_ALREADYANSWERED_MESSAGE);
            return responseEntity;
        } else if (!bool2) {
            responseEntity.setCode(Constants.FAIL_CODE);
            responseEntity.setMessage(Constants.ANSWER_QUESTIONNAIRENOTPUBLISHED_MESSAGE);
            return responseEntity;
        }
        responseEntity.setCode(Constants.FAIL_CODE);
        responseEntity.setMessage(Constants.LOGIN_FAIL_MESSAGE);
        return responseEntity;
    }

    /**
     * created by tkj 发送用户验证码
     *
     * @param map 传入的数据（"email"-String,"code"-String）目标地址邮箱和验证码（用String）
     * @return 统一的对象
     */

    public ResponseEntity sendAnswerEmail(Map<String, Object> map) throws EmailException {
        ResponseEntity responseEntity = new ResponseEntity();
        String email = (String) map.get("email");
        String code = (String) map.get("code");
        EmailSender.simpleEmailSend(code, email);
        responseEntity.setData(1);
        responseEntity.setMessage(Constants.SEND_MESSAGE);
        responseEntity.setCode(Constants.SUCCESS_CODE);
        return responseEntity;
    }


    public boolean isAnsweredQuestionnaire(String answerName, String qid) {
        List<Map<String, Object>> list = answerMapper.isAnsweredQuestionnaire(answerName, qid);
        long count = (Long) list.get(0).get("counts");
        if (count == 0) {
            return false;
        } else {
            return true;
        }
    }

}